/**
 * 功能降级处理器 - 在MCP服务不可用时提供降级策略
 */

export enum DegradationLevel {
  FULL_FUNCTIONALITY = 'full',      // 完整功能
  PARTIAL_DEGRADATION = 'partial',  // 部分降级
  MINIMAL_FUNCTIONALITY = 'minimal', // 最小功能
  EMERGENCY_MODE = 'emergency'       // 应急模式
}

export interface DegradationStatus {
  level: DegradationLevel;
  reason: string;
  timestamp: Date;
  affectedFeatures: string[];
  fallbackOptions: string[];
}

/**
 * 降级策略配置
 */
export interface DegradationStrategy {
  level: DegradationLevel;
  condition: () => boolean;
  actions: Array<() => Promise<void> | void>;
  message: string;
  fallbackFeatures: string[];
}

/**
 * 功能降级管理器
 */
export class DegradationHandler {
  private currentStatus: DegradationStatus;
  private strategies: DegradationStrategy[] = [];
  private statusListeners: Array<(status: DegradationStatus) => void> = [];
  private monitoringInterval: NodeJS.Timeout | null = null;

  constructor() {
    this.currentStatus = {
      level: DegradationLevel.FULL_FUNCTIONALITY,
      reason: '系统正常运行',
      timestamp: new Date(),
      affectedFeatures: [],
      fallbackOptions: []
    };

    this.initializeDefaultStrategies();
    this.startMonitoring();
  }

  /**
   * 初始化默认降级策略
   */
  private initializeDefaultStrategies(): void {
    // 策略1：MCP服务器部分不可用
    this.strategies.push({
      level: DegradationLevel.PARTIAL_DEGRADATION,
      condition: () => this.checkPartialMCPFailure(),
      actions: [
        () => this.disableAffectedTools(),
        () => this.notifyUserAboutLimitedFeatures()
      ],
      message: '部分MCP服务器不可用，某些工具功能将受限',
      fallbackFeatures: ['基础AI对话', '可用工具列表']
    });

    // 策略2：所有MCP服务器不可用
    this.strategies.push({
      level: DegradationLevel.MINIMAL_FUNCTIONALITY,
      condition: () => this.checkFullMCPFailure(),
      actions: [
        () => this.disableAllTools(),
        () => this.enableBasicAIOnly()
      ],
      message: 'MCP服务器不可用，仅提供基础AI对话功能',
      fallbackFeatures: ['基础AI对话', '消息历史']
    });

    // 策略3：AI服务也出现问题
    this.strategies.push({
      level: DegradationLevel.EMERGENCY_MODE,
      condition: () => this.checkAIServiceFailure(),
      actions: [
        () => this.enableEmergencyMode(),
        () => this.showEmergencyInstructions()
      ],
      message: 'AI服务出现问题，已切换到应急模式',
      fallbackFeatures: ['系统状态查看', '错误报告']
    });
  }

  /**
   * 添加状态监听器
   */
  addStatusListener(listener: (status: DegradationStatus) => void): () => void {
    this.statusListeners.push(listener);
    return () => {
      const index = this.statusListeners.indexOf(listener);
      if (index > -1) {
        this.statusListeners.splice(index, 1);
      }
    };
  }

  /**
   * 开始监控系统状态
   */
  private startMonitoring(): void {
    this.monitoringInterval = setInterval(() => {
      this.evaluateSystemStatus();
    }, 5000); // 每5秒检查一次
  }

  /**
   * 停止监控
   */
  private stopMonitoring(): void {
    if (this.monitoringInterval) {
      clearInterval(this.monitoringInterval);
      this.monitoringInterval = null;
    }
  }

  /**
   * 评估系统状态并应用相应的降级策略
   */
  private async evaluateSystemStatus(): Promise<void> {
    // 按照严重程度排序检查策略
    const sortedStrategies = this.strategies.sort((a, b) => {
      const levelOrder = {
        [DegradationLevel.EMERGENCY_MODE]: 4,
        [DegradationLevel.MINIMAL_FUNCTIONALITY]: 3,
        [DegradationLevel.PARTIAL_DEGRADATION]: 2,
        [DegradationLevel.FULL_FUNCTIONALITY]: 1
      };
      return levelOrder[b.level] - levelOrder[a.level];
    });

    for (const strategy of sortedStrategies) {
      if (strategy.condition()) {
        await this.applyDegradationStrategy(strategy);
        return;
      }
    }

    // 如果没有触发任何降级策略，恢复完整功能
    if (this.currentStatus.level !== DegradationLevel.FULL_FUNCTIONALITY) {
      await this.restoreFullFunctionality();
    }
  }

  /**
   * 应用降级策略
   */
  private async applyDegradationStrategy(strategy: DegradationStrategy): Promise<void> {
    if (this.currentStatus.level === strategy.level) {
      return; // 已经处于该降级级别
    }

    console.log(`应用降级策略: ${strategy.level} - ${strategy.message}`);

    // 执行降级动作
    for (const action of strategy.actions) {
      try {
        await action();
      } catch (error) {
        console.error('降级动作执行失败:', error);
      }
    }

    // 更新状态
    this.currentStatus = {
      level: strategy.level,
      reason: strategy.message,
      timestamp: new Date(),
      affectedFeatures: this.getAffectedFeatures(strategy.level),
      fallbackOptions: strategy.fallbackFeatures
    };

    this.notifyStatusListeners();
  }

  /**
   * 恢复完整功能
   */
  private async restoreFullFunctionality(): Promise<void> {
    console.log('恢复完整功能');

    try {
      // 重新启用所有功能
      await this.enableAllFeatures();

      this.currentStatus = {
        level: DegradationLevel.FULL_FUNCTIONALITY,
        reason: '系统已恢复正常',
        timestamp: new Date(),
        affectedFeatures: [],
        fallbackOptions: []
      };

      this.notifyStatusListeners();
    } catch (error) {
      console.error('恢复完整功能失败:', error);
    }
  }

  /**
   * 检查MCP部分故障
   */
  private checkPartialMCPFailure(): boolean {
    // 这里应该检查实际的MCP服务器状态
    // 暂时返回false，实际实现时需要与mcpManager集成
    try {
      // 检查是否有部分MCP服务器不可用但不是全部
      // const availableServers = mcpManager.getAllServers().filter(s => s.status === 'running');
      // const totalServers = mcpManager.getAllServers().length;
      // return availableServers.length > 0 && availableServers.length < totalServers;
      return false;
    } catch {
      return false;
    }
  }

  /**
   * 检查MCP完全故障
   */
  private checkFullMCPFailure(): boolean {
    try {
      // 检查是否所有MCP服务器都不可用
      // const availableServers = mcpManager.getAllServers().filter(s => s.status === 'running');
      // return availableServers.length === 0;
      return false;
    } catch {
      return true; // 如果无法检查，认为服务不可用
    }
  }

  /**
   * 检查AI服务故障
   */
  private checkAIServiceFailure(): boolean {
    try {
      // 检查AI服务是否可用
      // 可以通过ping或健康检查接口来验证
      return false;
    } catch {
      return true;
    }
  }

  /**
   * 禁用受影响的工具
   */
  private async disableAffectedTools(): Promise<void> {
    console.log('禁用受影响的工具');
    // 实现禁用特定工具的逻辑
  }

  /**
   * 通知用户功能受限
   */
  private async notifyUserAboutLimitedFeatures(): Promise<void> {
    console.log('通知用户某些功能受限');
    // 实现用户通知逻辑
  }

  /**
   * 禁用所有工具
   */
  private async disableAllTools(): Promise<void> {
    console.log('禁用所有MCP工具');
    // 实现禁用所有工具的逻辑
  }

  /**
   * 启用仅基础AI功能
   */
  private async enableBasicAIOnly(): Promise<void> {
    console.log('启用仅基础AI对话功能');
    // 实现基础AI功能的逻辑
  }

  /**
   * 启用应急模式
   */
  private async enableEmergencyMode(): Promise<void> {
    console.log('启用应急模式');
    // 实现应急模式的逻辑
  }

  /**
   * 显示应急说明
   */
  private async showEmergencyInstructions(): Promise<void> {
    console.log('显示应急模式使用说明');
    // 实现应急说明显示逻辑
  }

  /**
   * 启用所有功能
   */
  private async enableAllFeatures(): Promise<void> {
    console.log('启用所有功能');
    // 实现恢复所有功能的逻辑
  }

  /**
   * 获取受影响的功能列表
   */
  private getAffectedFeatures(level: DegradationLevel): string[] {
    switch (level) {
      case DegradationLevel.PARTIAL_DEGRADATION:
        return ['部分工具调用', '某些文件操作'];
      case DegradationLevel.MINIMAL_FUNCTIONALITY:
        return ['所有工具调用', '文件操作', '外部服务集成'];
      case DegradationLevel.EMERGENCY_MODE:
        return ['AI对话', '工具调用', '文件操作', '外部服务集成'];
      default:
        return [];
    }
  }

  /**
   * 通知状态监听器
   */
  private notifyStatusListeners(): void {
    this.statusListeners.forEach(listener => {
      try {
        listener(this.currentStatus);
      } catch (error) {
        console.error('状态监听器执行失败:', error);
      }
    });
  }

  /**
   * 获取当前降级状态
   */
  getCurrentStatus(): DegradationStatus {
    return { ...this.currentStatus };
  }

  /**
   * 手动触发降级
   */
  async forceDegradation(level: DegradationLevel, reason: string): Promise<void> {
    const strategy = this.strategies.find(s => s.level === level);
    if (strategy) {
      strategy.message = reason;
      await this.applyDegradationStrategy(strategy);
    }
  }

  /**
   * 手动恢复功能
   */
  async forceRestore(): Promise<void> {
    await this.restoreFullFunctionality();
  }

  /**
   * 添加自定义降级策略
   */
  addStrategy(strategy: DegradationStrategy): void {
    this.strategies.push(strategy);
  }

  /**
   * 获取可用的降级选项
   */
  getAvailableFallbacks(): string[] {
    return this.currentStatus.fallbackOptions;
  }

  /**
   * 检查功能是否可用
   */
  isFeatureAvailable(featureName: string): boolean {
    return !this.currentStatus.affectedFeatures.includes(featureName);
  }

  /**
   * 清理资源
   */
  cleanup(): void {
    this.stopMonitoring();
    this.statusListeners.length = 0;
    this.strategies.length = 0;
  }
}

// 导出单例
export const degradationHandler = new DegradationHandler();